package com.aifeng.hassan_food.mine

import android.annotation.SuppressLint
import android.os.Bundle
import com.aifeng.base.BaseActivity
import com.aifeng.base.loadRoundedImage
import com.aifeng.common_ui.base.gone
import com.aifeng.common_ui.base.oneClick
import com.aifeng.common_ui.base.visible
import com.aifeng.common_ui.helper.*
import com.aifeng.hassan_food.R
import com.aifeng.hassan_food.WebActivity
import com.aifeng.utils.DialogHelper.showHintDialog
import com.aifeng.utils.DialogHelper.showPayDialog
import com.aifeng.utils.bindLifeCycle
import com.aifeng.utils.subscribeBy
import com.aifeng.utils.subscribeByNoError
import com.aifeng.viewmodel.WalletViewModel
import com.kongqw.wechathelper.WeChatHelper
import com.kongqw.wechathelper.listener.auth
import kotlinx.android.synthetic.main.activity_wallet.*
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import org.koin.androidx.viewmodel.ext.android.getViewModel

class WalletActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_wallet)
        initTitle(title = "我的钱包")
    }

    @SuppressLint("SetTextI18n")
    override fun onStart() {
        super.onStart()
        wallet_money.text = getString("balance").formatDecimal()

        if (getString("bankCard").isNotEmpty()) {
            val bankNum = getString("bankCard")
            getViewModel().bankName(
                bankNum,
                getJsonFromAssets("bank_name.json")
            )
                .bindLifeCycle(getLifecycleOwner())
                .subscribeBy(
                    onNext = {
                        wallet_bank.text = "$it(尾号${bankNum.substring(bankNum.length - 4)})"
                        wallet_card.text = "更换"
                    }
                )
        }
    }

    override fun getViewModel() = getViewModel<WalletViewModel>()

    override fun initTitle(title: String, name: String, divider: Boolean) {
        super.initTitle(title, name, divider)
        if (getString("bindId").isNotEmpty()) {
            wallet_img.loadRoundedImage(getString("bindImg"))
            wallet_name.text = getString("bindName")
            wallet_weixin.text = "解绑"
        } else {
            wallet_img.gone()
            wallet_name.gone()
            wallet_weixin.text = "绑定"
        }

        wallet_info.oneClick { startActivity<WebActivity>("title" to "钱包协议") }
        wallet_detail.oneClick { startActivity<WalletDetailActivity>() }
        wallet_card.oneClick {
            if (checkReal()) startActivity<WalletCardActivity>()
        }

        wallet_weixin.oneClick {
            if (checkReal()) {
                when (wallet_weixin.textString()) {
                    "绑定" -> {
                        WeChatHelper.getInstance(baseContext).auth {
                            onWeChatAuthLoginSuccess { _, user ->
                                user?.let {
                                    bindWX(
                                        it.openid ?: "",
                                        it.nickname ?: "",
                                        it.headimgurl ?: ""
                                    )
                                }
                            }
                        }
                    }
                    "解绑" -> {
                        showHintDialog(
                            title = "解除绑定",
                            hint = "是否确定要解除当前绑定的账户？"
                        ) { unbind() }
                    }
                }
            }
        }

        bt_cash.oneClick {
            if (getString("balance").toNotDouble() <= 0) {
                toast("暂无可提现余额！")
                return@oneClick
            }

            if (getString("bankCard").isEmpty()) {
                toast("请先绑定银行卡！")
                return@oneClick
            }

            startActivity<WalletApplyActivity>()
        }
    }

    private fun unbind() {
        showPayDialog() {
            getViewModel().unbind(getString("userId"), it)
                .bindLifeCycle(getLifecycleOwner())
                .subscribeByNoError(
                    event = getViewModel(),
                    onSuccess = {
                        toast("解绑成功！")

                        clearShared("bindId", "bindImg", "bindName")

                        wallet_img.gone()
                        wallet_name.gone()
                        wallet_weixin.text = "绑定"
                    }
                )
        }
    }

    private fun bindWX(id: String, nick: String, img: String) {
        getViewModel().bank(
            "userid" to getString("userId"),
            "bind_wx_id" to id,
            "bind_wx_nick" to nick,
            "bind_wx_img" to img
        )
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByNoError(
                event = getViewModel(),
                onSuccess = {
                    toast("绑定微信成功！")
                    putShared("bindId", id)
                    putShared("bindImg", nick)
                    putShared("bindName", img)

                    wallet_img.visible()
                    wallet_name.visible()
                    wallet_weixin.text = "解绑"
                    wallet_name.text = nick
                    wallet_img.loadRoundedImage(img)
                }
            )
    }

    private fun checkReal() =
        if (getString("realName").isEmpty()) {
            showHintDialog(
                title = "实名认证",
                hint = "您还未进行实名认证，是否现在去认证？",
                sure = "去认证"
            ) { startActivity<RealActivity>() }
            false
        } else true

}
